const { json } = require('express');
const express = require('express')
const router = express.Router();
module.exports = router

const db = require('../db/temHandle')
const {formatData} = require('../utils')

// 获取列表 ( GET /api/record/list)
router.get('/list', async (req, res) => {
    const username = req.query
    const result = await db.read()
    if (result) {
        res.send({
            data:result,
            code:200,
            msg:"成功"
        })
    } else {
        res.send(formatData.fail())
    }
})

// 获取单个用户信息 ( GET /api/record/:id)
router.get('/:id',async (req, res) => {
    let {userId} = req.query;
    const result = await db.query(userId)
    if (result) {
        res.send({
                    data:result,
                    code:200,
                    msg:"成功"
                })
    } else {
        res.send(formatData.fail())
    }
})

// 新增 ( put /api/record/add) userId是必需 返回的master:[],f:[]
router.put('/add',async (req, res) => {
    const obj = req.body
    try {
        const result = await db.create(obj)
        res.send(formatData())

    } catch (err) {
        res.send(formatData.fail())
    }
})

// 修改信息 ( put /api/record/update/:id)   userId是必需
router.put('/update/:id',async (req, res) => {
    const obj = req.body
    try {
        const result = await db.update(obj)
        res.send(formatData())
    } catch (err) {
        res.send(formatData({ code: 400 }));
    }
})

// 删除 ( delete /api/record/delete/:id)
router.delete('/delete/:id',async (req, res) => {
    const { userId } = req.body;
    try {
        const result = await db.delete(userId)
        res.send(formatData())
    } catch (err) {
        res.send(formatData({ code: 400 }));
    }
})